package com.gykfbxxh.imovie.view.main.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;

import com.android.volley.VolleyError;
import com.app.utils.util.LogUtils;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.AppApplication;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.adapter.FilmsAdapter;
import com.gykfbxxh.imovie.base.BaseListFragment;
import com.gykfbxxh.imovie.bean.film.FilmEntity;
import com.gykfbxxh.imovie.bean.film.FilmList;
import com.gykfbxxh.imovie.config.TypeConstant;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.utils.HttpUtils;
import com.gykfbxxh.imovie.videoplayer.JCVideoPlayer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuxinghai
 * On 2017/8/25
 * 电影fragment
 */

public class FilmsFragment extends BaseListFragment<FilmEntity> {
    /*********
     * 逻辑数据
     **********/
    private String mChannelId;//栏目id
    private String mChannelName;//栏目名称
    private String mChannelType;//栏目类型
    private boolean isFocus;//是否是聚焦栏目
    private Activity mActivity;
    private ViewGroup mContentView;//根布局

    private boolean isStop;//listView是否停止
    private int mMark;//下拉刷新请求标识

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        mChannelId = (args != null ? args.getString("id", "0") : "0");
        mChannelName = (args != null ? args.getString("name", "null") : "null");
        mChannelType = (args != null ? args.getString("type", null) : null);
        isFocus = (args != null && !TextUtils.isEmpty(args.getString("focus_news")));
    }

    @Override
    public void onAttach(Activity activity) {
        mActivity = activity;
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void changeData(final boolean isRefresh) {
        HttpUtils.addGetRequest(URIContant.GETFILMLIST + mChannelId +"&pno="+dataPage, new TypeToken<FilmList>() {
        }.getType(), mPageName, new HttpListener<FilmList>() {

            @Override
            public void onStart() {
                setLoadView(LOADING, null);
                LogUtils.e("xuxh","onStart");
            }

            @Override
            public void onError(VolleyError error) {
                setLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror));
                LogUtils.e("xuxh","onError");
            }

            @Override
            public void onSuccess(FilmList response) {
                LogUtils.e("xuxh","onSuccess");
                if(response!=null&&response.getResult()!=null){
                    FilmList.ResultBean result = response.getResult();
                    if(result!=null) {
                        List<FilmEntity> list = result.getList();
                        if(list!=null&&list.size()>0) {
                            if(dataList == null) {
                                dataList = new ArrayList<FilmEntity>();
                            }
                            if(isRefresh) {
                                dataList.clear();
                            }
                            dataList.addAll(list);
                            if (mAdapter == null) {
                                mAdapter = new FilmsAdapter(dataList, activity, mChannelType, onClick);
                                //mAdapter = new NewsAdapter(dataList, activity, mChannelType,NewsFragment1.this);
                                mListView.setAdapter(mAdapter);
                            } else {
                                mAdapter.notifyDataSetChanged();
                            }
                            if (isRefresh) {
                                if (list.size() > 1) {
                                    String msg = "推荐引擎有<font color='#F9D13F'>" + (list.size() ) + "</font>条新数据";
                                    setLoadView(LOADSUCES, Html.fromHtml(msg));
                                } else {
                                    //updateLoadView(LOADSUCES, "暂无新数据");
                                    setLoadView(LOADSUCES, getString(R.string.pullup_nomore_data));
                                }
                            } else {
                                setLoadView(LOADSUCES, "");
                            }

                        }else {
                            setLoadView(LOADSUCES, getString(R.string.pullup_nomore_data));
                        }
                    }else {
                        setLoadView(DATAERROR, response.getErrorMsg());
                    }
                }else {
                    setLoadView(DATAERROR, response.getErrorMsg());
                }
            }
        });
    }

    /**
     * 去除无效数据
     * @param list
     * @param b
     */
    private void dataRevisited(List<FilmEntity> list, boolean b) {
//        if (list == null || list.size() == 0) {
//            return;
//        }
//        for (int i = 0; i < list.size(); i++) {
//            if (i >= list.size()) {
//                break;
//            }
//            FilmEntity listBean = list.get(i);
//            if(listBean==null) {
//                continue;
//            }
//
//        }
    }


    /**
     * LoadViewd 方法
     *
     * @param code 传入对应的值
     * @param msg  提示的的文字
     */
    protected void setLoadView(int code, CharSequence msg) {

        switch (code) {
            case NO_NET://网络错误
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showErrorPage(msg);
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                        }
                    }, 800);
                }
                break;
            case DATAERROR://数据错误
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showErrorPage(msg);
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                        }
                    }, 800);
                }
                break;
            case LOADING://加载中
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showLoadPage(msg);
                }
                break;
            case LOADSUCES://加载成功
                if (dataList != null && dataList.size() > 0) {
                    mLoadView.showSuccess();
                } else {
                    mLoadView.showEmptyPage(TypeConstant.EMPTY_DEFAULT, "");
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                        }
                    }, 800);
                }
                break;
        }
        if (msg != null && !"".equals(msg)) {
            notify_view_text.setText(msg);
            notify_view_text.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    notify_view_text.setVisibility(View.GONE);
                }
            }, 2000);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    protected void changeView() {
//        mLoadView.showSuccess();
        mListView.getRefreshableView().setOnScrollListener(new AbsListView.OnScrollListener() {

            int firstPosition = 1;//上一次的第一个位置
            int lastPosition;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (isStop && !mListView.isRefreshing()) {
//                        isStop=false;
                        mListView.showFootView();
//				mListView.getRefreshableView().setSelection(newsList.size());
                        onPullUpToRefresh(mListView);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (JCVideoPlayer.IS_FULLSCREEN) {
                    return;
                }
                if ((totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount )) {
                    isStop = true;
                } else {
                    isStop = false;
                }

            }
        });
    }

    /**
     * 刷新 downview
     */
    public void notifyDown() {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void startActivity(Intent intent) {
        if(activity!=null) {
            activity.startActivity(intent);
        }else {
            super.startActivity(intent);
        }
    }

    private View.OnClickListener onClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.ll_like:
                    FilmEntity filmEntity = (FilmEntity) v.getTag(R.id.tag_first);
                    ToastUtils.makeText("点击了"+filmEntity.getFName()+"喜欢");
                    break;
                case R.id.ll_share:
                    FilmEntity filmEntity1 = (FilmEntity) v.getTag(R.id.tag_first);
                    ToastUtils.makeText("点击了"+filmEntity1.getFName()+"分享");
                    break;
                case R.id.ll_more:
                    FilmEntity filmEntity2 = (FilmEntity) v.getTag(R.id.tag_first);
                    ToastUtils.makeText("点击了"+filmEntity2.getFName()+"更多");
                    break;
            }
        }
    };

}
